package com.xnew.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 
 * @Description: http请求工具类
 * @author: huanghai
 * @date: 2019-08-07
 * @version: V1.0
 */
public class HttpClientUtil {

	private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);

	/**
	 * 发送Post请求,JSON格式
	 * 
	 * @param url
	 * @param param
	 * @return
	 */
	public static String sendPostJSON(String url, String param) {
		return sendPostJSON(url, param, 10 * 1000);
	}

	/**
	 * 发送Post请求,JSON格式
	 * 
	 * @param url
	 *            地址
	 * @param param
	 *            json字符串
	 * @param timeout
	 *            时长(毫秒)
	 * @return
	 */
	public static String sendPostJSON(String url, String param, int timeout) {
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpPost method = new HttpPost(url);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
					.build();
			method.setConfig(requestConfig);
			StringEntity entity = new StringEntity(param, "UTF-8");
			entity.setContentEncoding("UTF-8");
			entity.setContentType("application/json");
			method.setEntity(entity);
			CloseableHttpResponse result = httpClient.execute(method);
			String resData = EntityUtils.toString(result.getEntity(), "UTF-8");
			return resData;
		} catch (Exception e) {
			return "";
		}
	}
	public Map<String, String> doPost(String url, Map<String,String> params, String charset){
		Map<String, String> map = new HashMap<String, String>();
		HttpClient httpClient = null;
		HttpPost httpPost = null;
		String result = null;
		int status = 0;
		try{
			httpClient = new SSLClient();
			httpPost = new HttpPost(url);
			httpPost.setHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
			httpPost.setHeader("Connection", "Close");
			//设置参数
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
			while(iterator.hasNext()){
				Map.Entry<String,String> elemment = (Map.Entry<String, String>) iterator.next();
				list.add(new BasicNameValuePair(elemment.getKey(),elemment.getValue()));
			}
			if(list.size() > 0){
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
				httpPost.setEntity(entity);
			}
			HttpResponse response = httpClient.execute(httpPost);
			status = response.getStatusLine().getStatusCode();
			//System.out.println("status==============="+status);
			if(response != null){
				HttpEntity resEntity = response.getEntity();
				if(resEntity != null){
					result = EntityUtils.toString(resEntity,charset);
					//System.out.println("result==============="+result);
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		map.put("status", String.valueOf(status));
		map.put("result", result);
		return map;
	}

	public Map<String, String> doGet(String url, Map<String,String> params,String charset){
		Map<String, String> map = new HashMap<String, String>();
		String result = null;
		int status = 0;
		HttpClient httpClient = null;
		try{
			httpClient = new SSLClient();
			// 创建访问的地址
			URIBuilder uriBuilder = new URIBuilder(url);
			if (params != null) {
				Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
				Map.Entry<String, String> entry;
				while (iterator.hasNext()) {
					entry = iterator.next();
					uriBuilder.setParameter(entry.getKey(), entry.getValue() == null ? "" : entry.getValue());
				}
			}
			HttpGet httpGet = new HttpGet(uriBuilder.build());
			httpGet.setHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
			httpGet.setHeader("Connection", "Close");
			HttpResponse response = httpClient.execute(httpGet);

			status = response.getStatusLine().getStatusCode();
			//System.out.println("status==============="+status);
			if(response != null){
				HttpEntity resEntity = response.getEntity();
				if(resEntity != null){
					result = EntityUtils.toString(resEntity, charset);
					//System.out.println("result==============="+result);
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		map.put("status", String.valueOf(status));
		map.put("result", result);
		return map;
	}
}
